Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

190
Vistas
Using the boolean "True" as an expression to evaluate in a while loop

I recently was making a little script that would ask for tv series titles and logs them on the console in an array. I used a keyword to stop the loop which is 'terminate' and it should not be included, however, the following code adds the keyword to the array.

//-----------------firts case code ------------------//

let lista = [];
let series;

function collect(){
  while (series !== 'terminate'){
    series = prompt('Add a tv show');
    lista.push(series);
  }
}

collect();

console.log(lista);

More confusing still, is that in the next piece of code, I managed to make the script to leave the keyword out of the array.

//---------------------------Second case code--------------------------//

let lista2 = [];
let series;

while (true){
  series2 = prompt('add tv serie');
  if (series2 !=='terminate'){
    lista2.push(series2);
  }else{
    break;
  }
}
console.log(lista2);

My question is, how the use of the boolean as the expression to evaluate in a loop affects the result as opposed to the first case scenario with the first case code?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Basically you need to have a check between input and adding the string to the array.

For looping forever, you need an expression which evaluates to a truthy value. This value is a constant value as opposed of the check with two strings series2 !== 'terminate'.

You could terminate the loop inside with an if statement and break.

Addtionaly, you could check for null and use the return value of prompt for being cancelled.

function collect() {
    while (true) {
        const series = prompt('Add a tv show');
        if (series === 'terminate' || series === null) break;
        lista.push(series);
    }
}

let lista = [];

collect();
console.log(lista);

Another approach by using prompt twice.

function collect() {
    let series = prompt('Add a tv show');

    while (series !== 'terminate' && series !== null) {
        lista.push(series);
        series = prompt('Add a tv show');
    }
}

let lista = [];

collect();
console.log(lista);

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda